//配置路由信息

//引入vue
import Vue from 'vue'
//引入Vue-router
import VueRouter from 'vue-router'
//引入路径信息
import routes from './routes';
//引入store
import store from '@/store';

//使用路由
Vue.use(VueRouter);

//解决编程式导航，多次执行同一参数请求抛出错误的问题
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function(location, resolve, reject) {
    console.log(this);
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => {}, () => {})
    }
}

VueRouter.prototype.replace = function(location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => {}, () => {})
    }
}

//配置路由
let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }

})
router.beforeEach(async(to, from, next) => {
    //获取token
    let token = store.state.user.token;
    //获取用户信息
    let userInfo = store.state.user.userInfo.name;
    //登录状态
    if (token) {
        //不让去登录页
        if (to.path == '/login') {
            next('/home')
        } else {
            //用户信息是否存在
            if (userInfo) {
                next();
            } else {
                //用户信息不存在，重新派发action
                try {
                    await store.dispatch('userInfo');
                    next();
                } catch (error) {
                    //请求失败，说明toke过期，清除用户信息，回到登录页面
                    await store.dispatch('logout');
                    next('/login')
                }
            }
        }
    } else {
        if (to.path == '/addCartSuccess' || to.path == '/shopCart' || to.path == '/pay' || to.path == '/paySuccess' || to.path == '/center' || to.path == '/center/personalOrder' || to.path == '/center/groupOrder' || to.path == '/trade') {
            next(`/login?redirect=` + to.path)
        } else {
            next()
        }
    }
})

//对外暴露
export default router;